import os
import pickle
from io import StringIO
from io import BytesIO
# 文件读写
# 写法一:
# try:
#     f = open('/Project/PythonProject/test.txt', 'r')
#     print(f.read())                 # 读取文件中的所有内容
# finally:
#     if f:
#         f.close()

# 写法二:
with open('/Project/PythonProject/test.txt', 'r', encoding = 'gbk') as f:      # with语句会自动调用close()方法
    for line in f.readlines():
        print(line.strip())           # 去掉末尾的'\n'

with open('/Project/PythonProject/test.txt', 'a') as f:
    f.write('\nHello Python!')

# StringIO
f = StringIO()
f.write('Hello')
f.write(' ')
f.write('World!')
f.seek(0)                    # 调用f.readlines()时必须使用将stream position置为 0
print(f.readlines())

# ByteIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())

# 操作文件和目录
print(os.name)                                      # nt表示Windows系统
print(os.path.abspath('.'))                         # 查看当前目录下的绝对路径

os.mkdir(os.path.join('/Project/PythonProject', 'testdir'))          # 创建目录
os.rmdir(os.path.join('/Project/PythonProject', 'testdir'))          # 删除目录

print(os.path.split('/Project/PythonProject/test.txt'))              # 拆分目录（最后级别的目录/文件名）
print(os.path.splitext('/Project/PythonProject/test.txt'))           # 拆分目录（拓展名）

# os.rename('test.txt', 'test.py')                                   # 文件重命名

print([x for x in os.listdir('.') if os.path.isdir(x)])
print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py'])     # 文件过滤

# 序列化: 将变量从内存中变成可存储或传输的过程(未完成)
# 反之，将变量内容从序列化的对象重新读到内存里称之为反序列化
d1 = dict(name = 'Bob', age = 20, score = 88)
pickle.dumps(d1)
f = open('dump.txt', 'wb')
pickle.dump(d1, f)
f.close()

f = open('dump.txt', 'rb')
d2 = pickle.load(f)
f.close()
print(d2)

# 注意：Python的矩阵操作和关于单纯形法的实现将作为下一步工作重点